import { type ComponentInternalInstance, getCurrentInstance } from 'vue'
import { baseUrl } from '@/configs'

export const genStaticUrl = (url?: string) => {
	if (url === '' || url == null) return ''

	if (url.startsWith('http')) return url

	return `${baseUrl}${url.startsWith('/') ? '' : '/'}${url}`
}

//获取多少分钟时间
function getDateTimeStamp (dateStr:number | string) {
  if (typeof dateStr === 'number') {
    return new Date(dateStr).getTime() * 1000
  }
  if (!dateStr) return 0
  return Date.parse(dateStr.replace(/-/g, "/"));
}
export function getDateDiff (dateStr:number | string) {
   let publishTime = getDateTimeStamp(dateStr) ,
    d_seconds:any,
    d_minutes:any,
    d_hours:any,
    d_days:any,
    timeNow:any = parseInt(new Date().getTime() ),
    d:any,
    date:any = new Date(publishTime ),
    Y:any = date.getFullYear(),
    M:any = date.getMonth() + 1,
    D :any= date.getDate(),
    H :any= date.getHours(),
    m:any = date.getMinutes(),
    s :any= date.getSeconds();
  //小于10的在前面补0
  if (M < 10) {
    M = '0' + M;
  }
  if (D < 10) {
    D = '0' + D;
  }
  if (H < 10) {
    H = '0' + H;
  }
  if (m < 10) {
    m = '0' + m;
  }
  if (s < 10) {
    s = '0' + s;
  }

  d = timeNow - publishTime;
  d_days = parseInt(d / 86400);
  d_hours = parseInt(d / 3600);
  d_minutes = parseInt(d / 60);
  d_seconds = parseInt(d);

  if (d_days > 0 && d_days < 3) {
    return d_days + '天前';
  } else if (d_days <= 0 && d_hours > 0) {
    return d_hours + '小时前';
  } else if (d_hours <= 0 && d_minutes > 0) {
    return d_minutes + '分钟前';
  } else if (d_seconds < 60) {
    if (d_seconds <= 0) {
      return '刚刚';
    } else {
      return d_seconds + '秒前';
    }
  } else if (d_days >= 3 && d_days < 30) {
    return M + '-' + D + ' ' + H + ':' + m;
  } else if (d_days >= 30) {
    return Y + '-' + M + '-' + D + ' ' + H + ':' + m;
  }
}
/**
 * 延迟等待
 *
 * @param {string} [delay=300] - 延迟时间(毫秒).
 * @returns {string} 等待完成后的Promise.
 */
export const delayed = (delay : number = 300) : Promise<void> => {
	return new Promise<void>((resolve) => {
		const timer = setTimeout(() => {
			resolve()

			clearTimeout(timer)
		}, delay)
	})
}

/**
 * 生成uuid
 *
 * @returns {string} uuid字符串.
 */
export const generateUUID = () : string => {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
		const r = (Math.random() * 16) | 0
		const v = c === 'x' ? r : (r & 0x3) | 0x8
		return v.toString(16)
	})
}

/**
 * 格式化查询字符串
 *
 * @param {string} url - 请求路径.
 * @param {object} params - 请求参数.
 * @returns {string} 查询字符串.
 */
export function formatQuery(url : string, params : { [key : string] : any }) : string {
	let path = `${url}?`

	for (const key in params) {
		path += `${key}=${params[key]}&`
	}

	return path.substring(0, path.length - 1)
}

/**
 * 时间格式化
 *
 * @param {number} timestamp - 时间戳.
 * @param {string} format    - 时间格式（默认：yyyy-mm-dd）.
 * @returns {string} 返回格式化的时间.
 */
export function timeFormat(timestamp : number, format : string = 'yyyy-mm-dd') : string {
	// const fullTimestamp = Number(`${timestamp}`.padEnd(13, '0'))
	// const date = new Date(fullTimestamp)
	const date = new Date(timestamp )

	const formats = <{
		[key : string] : number
	}>{
			yyyy: date.getFullYear(),
			mm: date.getMonth() + 1,
			dd: date.getDate(),
			hh: date.getHours(),
			MM: date.getMinutes(),
			ss: date.getSeconds(),
		}

	let result = format.trim()

	for (const key in formats) {
		const value = formats[key].toString().padStart(2, '0')

		result = result.split(key).join(value)
	}

	return result
}

export function isEmpty(value: unknown) {
	if (value == null) return true

	if (typeof value === 'string' || Array.isArray(value)) return value.length === 0

	if (typeof value === 'object' && value !== null) return Object.keys(value).length === 0

	return false
}

export function genRandomId(prefix?: string) {
	const randomId = Math.random().toString(16).slice(2)

	if (prefix) return `${prefix}_${randomId}`

	return randomId
}

/**
 * 获取节点信息
 * @param {string} selector
 * @param {boolean} selectAll
 * @param {ComponentInternalInstance | null} context
 * @return
 */
export function getNodeRect(selector: string, context?: ComponentInternalInstance | null): Promise<UniApp.NodeInfo>;
export function getNodeRect(selector: string, selectAll: false, context?: ComponentInternalInstance | null): Promise<UniApp.NodeInfo>;
export function getNodeRect(selector: string, selectAll: true, context?: ComponentInternalInstance | null): Promise<UniApp.NodeInfo[]>;
export function getNodeRect(selector: string, selectAll?: boolean | ComponentInternalInstance | null, context?: ComponentInternalInstance | null) {
		return new Promise<UniApp.NodeInfo | UniApp.NodeInfo[]>((resolve, reject) => {
			try {
				if (selectAll != null) {
					if (typeof selectAll !== 'boolean') {
						context = selectAll
						selectAll = false
					}
				}

				const vm = context ?? getCurrentInstance()
				const query = uni.createSelectorQuery().in(vm)

				query[selectAll === true ? 'selectAll' : 'select'](selector)
				  .boundingClientRect((rect) => {
						resolve(rect)
				  })
				  .exec()
			} catch (err) {
				reject(err)
			}
		})
}
